//
//  SettingsViewController.m
//  NXTRemoteController
//
//  Created by naceka on 14.05.12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "SettingsUIViewController.h"


@implementation SettingsUIViewController

@synthesize connectBtn;
@synthesize nxtId;
@synthesize leftMotor;
@synthesize rightMotor;
@synthesize sensor1;
@synthesize sensor2;
@synthesize sensor3;
@synthesize sensor4;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil andRobot:(Robot *) rbt {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
		robot = rbt;
		connected = false;
		
		//register in notification center
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceConnected) name:@"RobotDeviceConnected" object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceDisconnected) name:@"RobotDeviceDisconnected" object:nil];
    }
    return self;
}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.view.backgroundColor = [UIColor whiteColor];
	
	//some labels
	UILabel * nxtIdLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 10, 80, 30)];
	nxtIdLabel.backgroundColor = [UIColor clearColor];
	nxtIdLabel.text = @"NXT ID";
	nxtIdLabel.font = [UIFont boldSystemFontOfSize:15];
	[self.view addSubview:nxtIdLabel];
	
	UILabel * leftMotorLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 50, 80, 30)];
	leftMotorLabel.backgroundColor = [UIColor clearColor];
	leftMotorLabel.text = @"Левый";
	[self.view addSubview:leftMotorLabel];
	
	UILabel * rightMotorLabel = [[UILabel alloc] initWithFrame:CGRectMake(270, 50, 80, 30)];
	rightMotorLabel.backgroundColor = [UIColor clearColor];
	rightMotorLabel.text = @"Правый";
	[self.view addSubview:rightMotorLabel];
	
	UILabel * sensor1Label = [[UILabel alloc] initWithFrame:CGRectMake(30, 90, 90, 30)];
	sensor1Label.backgroundColor = [UIColor clearColor];
	sensor1Label.text = @"Сенсор #1";
	[self.view addSubview:sensor1Label];
	
	UILabel * sensor2Label = [[UILabel alloc] initWithFrame:CGRectMake(30, 130, 90, 30)];
	sensor2Label.backgroundColor = [UIColor clearColor];
	sensor2Label.text = @"Сенсор #2";
	[self.view addSubview:sensor2Label];
	
	UILabel * sensor3Label = [[UILabel alloc] initWithFrame:CGRectMake(30, 170, 90, 30)];
	sensor3Label.backgroundColor = [UIColor clearColor];
	sensor3Label.text = @"Сенсор #3";
	[self.view addSubview:sensor3Label];
	
	UILabel * sensor4Label = [[UILabel alloc] initWithFrame:CGRectMake(30, 210, 90, 30)];
	sensor4Label.backgroundColor = [UIColor clearColor];
	sensor4Label.text = @"Сенсор #4";
	[self.view addSubview:sensor4Label];
	
	
	//UITextField
	nxtId = [[UITextField alloc] initWithFrame:CGRectMake(140, 10, 260, 30)];
	nxtId.borderStyle = UITextBorderStyleRoundedRect;
	nxtId.font = [UIFont systemFontOfSize:15];
	//nxtId.placeholder = @"enter text";
	//nxtId.text = @"00165306CC15";
	nxtId.autocorrectionType = UITextAutocorrectionTypeNo;
	nxtId.keyboardType = UIKeyboardTypeDefault;
	nxtId.returnKeyType = UIReturnKeyDone;
	nxtId.clearButtonMode = UITextFieldViewModeWhileEditing;
	nxtId.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;   
	nxtId.delegate = self;
	[self.view addSubview:nxtId];
	//[nxtId release];
	
	//segmented controls
	leftMotor = [[UISegmentedControl alloc] initWithItems:[[NSArray alloc] initWithObjects:@"A", @"B", @"C", nil]];
	leftMotor.selectedSegmentIndex = 0;
	leftMotor.segmentedControlStyle = UISegmentedControlStyleBar;
	leftMotor.center = CGPointMake(160, 65);
	[self.view addSubview:leftMotor];
	
	rightMotor = [[UISegmentedControl alloc] initWithItems:[[NSArray alloc] initWithObjects:@"A", @"B", @"C", nil]];
	rightMotor.selectedSegmentIndex = 2;
	rightMotor.segmentedControlStyle = UISegmentedControlStyleBar;
	rightMotor.center = CGPointMake(370, 65);
	[self.view addSubview:rightMotor];
	
	sensor1 = [[UISegmentedControl alloc] initWithItems:[[NSArray alloc] initWithObjects:@"Нет", @"Такт", @"Свет", @"Звук", @"Ультразв", nil]];
	sensor1.selectedSegmentIndex = 0;
	sensor1.segmentedControlStyle = UISegmentedControlStyleBar;
	sensor1.frame = CGRectMake(120, 90, 300, 30);
	[self.view addSubview:sensor1];
	
	sensor2 = [[UISegmentedControl alloc] initWithItems:[[NSArray alloc] initWithObjects:@"Нет", @"Такт", @"Свет", @"Звук", @"Ультразв", nil]];
	sensor2.selectedSegmentIndex = 0;
	sensor2.segmentedControlStyle = UISegmentedControlStyleBar;
	sensor2.frame = CGRectMake(120, 130, 300, 30);
	[self.view addSubview:sensor2];
	
	sensor3 = [[UISegmentedControl alloc] initWithItems:[[NSArray alloc] initWithObjects:@"Нет", @"Такт", @"Свет", @"Звук", @"Ультразв", nil]];
	sensor3.selectedSegmentIndex = 0;
	sensor3.segmentedControlStyle = UISegmentedControlStyleBar;
	sensor3.frame = CGRectMake(120, 170, 300, 30);
	[self.view addSubview:sensor3];
	
	sensor4 = [[UISegmentedControl alloc] initWithItems:[[NSArray alloc] initWithObjects:@"Нет", @"Такт", @"Свет", @"Звук", @"Ультразв", nil]];
	sensor4.selectedSegmentIndex = 0;
	sensor4.segmentedControlStyle = UISegmentedControlStyleBar;
	sensor4.frame = CGRectMake(120, 210, 300, 30);
	[self.view addSubview:sensor4];
	
	connectBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[connectBtn addTarget:self action:@selector(connectPressed:) forControlEvents:UIControlEventTouchUpInside];
	[connectBtn setTitle:@"Соединиться" forState:UIControlStateNormal];
	connectBtn.frame = CGRectMake(181, 265, 120, 37);
	[self.view addSubview:connectBtn];
	
	indicatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 450, 350)];
	indicatorView.backgroundColor = [[UIColor alloc] initWithRed:0 green:0 blue:0 alpha:0.6];
	
	self.navigationItem.title = @"Настройки";
	
	//old data
	NSUserDefaults * user_defaults = [NSUserDefaults standardUserDefaults];
	NSString * nxt_id = [user_defaults objectForKey:@"nxtId"];
	if ([nxt_id length]) {
		//set nxt id
		nxtId.text = nxt_id;
		//motors
		leftMotor.selectedSegmentIndex = [user_defaults integerForKey:@"leftMotor"];
		rightMotor.selectedSegmentIndex = [user_defaults integerForKey:@"rightMotor"];
		//sensors
		sensor1.selectedSegmentIndex = [user_defaults integerForKey:@"sensor1Type"];
		sensor2.selectedSegmentIndex = [user_defaults integerForKey:@"sensor2Type"];
		sensor3.selectedSegmentIndex = [user_defaults integerForKey:@"sensor3Type"];
		sensor4.selectedSegmentIndex = [user_defaults integerForKey:@"sensor4Type"];		
	}	
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
	[super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;	
}


- (void)dealloc {
	
    [super dealloc];
}

- (IBAction) connectPressed:(id) sender {
	//get all data and connect
	
	if (!connected) {
		//if address correct
		if ([self checkNxtId:[nxtId text]]) {
			//register motors
			[robot registerLeftMotor:(enum Motor)[leftMotor selectedSegmentIndex]];
			[robot registerRightMotor:(enum Motor)[rightMotor selectedSegmentIndex]];
			
			//register sensor's
			[robot registerSensor:[self getSensorNameFromNumber:[sensor1 selectedSegmentIndex]] OnPort:0];
			[robot registerSensor:[self getSensorNameFromNumber:[sensor2 selectedSegmentIndex]] OnPort:1];
			[robot registerSensor:[self getSensorNameFromNumber:[sensor3 selectedSegmentIndex]] OnPort:2];
			[robot registerSensor:[self getSensorNameFromNumber:[sensor4 selectedSegmentIndex]] OnPort:3];
			
			//set nxt id before connect
			[robot setNxtId:&device_address];
			
			//connect
			[robot connect];
			
			connected = true;
			
			//change to disconnect
			[connectBtn setTitle:@"Отсоединиться" forState:UIControlStateNormal];
		
			//set widgets off
			[self setWidgetsState:NO];
			
			//start indicator
			[self showIndicator];
		
		}
		else {
			//error incorrect address
			UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Ошибка!" message:@"Неверно задан адрес" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alert show];
			[alert release];
		}
	}
	else {
		[robot disconnect];
	}
}

- (bool) checkNxtId:(NSString *) string {
	
	NSLog(@"check nxt id %@", string);
	if ([string length] == 12) {
		for (int i = 0; i < 6; i++) {
			unsigned int part;
			NSString * pstring = [string substringWithRange:NSMakeRange(i*2, 2)];
			NSScanner * scaner = [NSScanner scannerWithString:pstring];
			[scaner scanHexInt:&part];
			device_address[i] = (uint8_t)part;
		}
		return true;
	}
	
	return false;
}

- (Sensor *) getSensorNameFromNumber:(int) number {
	Sensor * retval = nil;
	
	switch (number) {
		case 0:
			retval = [[Sensor alloc] initWithType:NO_SENSOR andMode:RAWMODE];
			break;
		case 1:
			retval = [[Sensor alloc] initWithType:SWITCH andMode:BOOLEANMODE];
			break;
		case 2:
			retval = [[Sensor alloc] initWithType:LIGHT_INACTIVE andMode:RAWMODE];
			break;
		case 3:
			retval = [[Sensor alloc] initWithType:SOUND_DBA andMode:RAWMODE];
			break;
		case 4:
			retval = [[Sensor alloc] initWithType:LOWSPEED_9V andMode:RAWMODE];
			break;
		default:
			break;
	}
	
	return retval;
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	//for nxt id text editor
	[textField resignFirstResponder];
	return NO;
}

- (void) showIndicator {
	//view
	[self.view addSubview:indicatorView];
	
	//indicator
	indicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
	indicator.frame = CGRectMake(round((self.view.frame.size.width - 25) / 2), round((self.view.frame.size.height - 25) / 2), 25, 25);
	[self.view addSubview:indicator];
	[indicator startAnimating];
}

- (void) hideIndicator {
	//indicator
	[indicator stopAnimating];
	[indicator removeFromSuperview];
	indicator = nil;
	
	//view
	[indicatorView removeFromSuperview];
}

- (void) setWidgetsState:(BOOL) state {
	//set all widgets state to 'state'
	[nxtId setEnabled:state];
	[leftMotor setEnabled:state];
	[rightMotor setEnabled:state];
	[sensor1 setEnabled:state];
	[sensor2 setEnabled:state];
	[sensor3 setEnabled:state];
	[sensor4 setEnabled:state];
}

//RobotStateDelegate
- (void) deviceConnected {
	//save data
	NSUserDefaults * user_defaults = [NSUserDefaults standardUserDefaults];
	
	//set nxt id
	[user_defaults setObject:nxtId.text forKey:@"nxtId"];
	//motors
	[user_defaults setInteger:leftMotor.selectedSegmentIndex forKey:@"leftMotor"];
	[user_defaults setInteger:rightMotor.selectedSegmentIndex forKey:@"rightMotor"];
	//sensors
	[user_defaults setInteger:sensor1.selectedSegmentIndex forKey:@"sensor1Type"];
	[user_defaults setInteger:sensor2.selectedSegmentIndex forKey:@"sensor2Type"];
	[user_defaults setInteger:sensor3.selectedSegmentIndex forKey:@"sensor3Type"];
	[user_defaults setInteger:sensor4.selectedSegmentIndex forKey:@"sensor4Type"];	
	[user_defaults synchronize];
	
	//hide load indicator
	[self hideIndicator];
} 

- (void) deviceDisconnected {
	connected = false;
	
	//set widgets on
	[self setWidgetsState:YES];
	
	[connectBtn setTitle:@"Соединиться" forState:UIControlStateNormal];
}

@end